<?php
use Joomla\Registry\Registry;

defined('_JEXEC') or die;

class DoskaModelMessage extends JModelAdmin {

	public function getForm($data = array(), $loadData = true) {
		
		$form = $this->loadForm(
								$this->option.".message",
								"message",
								array('control' => 'jform', 'load_data' => $loadData));
		
		if (empty($form))
	    {
	        return false;
	    }
	 
	    return $form;
	}
	
	public function getTable($type = 'Message', $prefix = 'DoskaTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	
	protected function loadFormData()
	{
		$data = JFactory::getApplication()->getUserState(
			'com_doska.edit.message.data',
			array()
		);
		
		if (empty($data))
		{
			$data = $this->getItem();
		}

		return $data;
	}
	
	public  function getScript()
	{
		return '/administrator/components/com_doska/models/forms/button.js';
	}
	
	
	protected function prepareTable($table) {
		
		if((int)$table->created == 0) {
			$table->created = JFactory::getDate()->toSql();
		}
		
		if((int)$table->publish_up == 0 && $table->state == 1 ) {
			$table->publish_up = JFactory::getDate()->toSql();
		}
		
		if((int)$table->publish_down == 0 && $table->state == 1 ) {
			$table->publish_down = JFactory::getDate('+1 week')->toSql();
		}
		
		
	}
	
	public function save($data) {
		
		$data['id_user'] = JFactory::getUser()->id;
		
		$config = JComponentHelper::getParams('com_doska');
		
		if(!trim($data['title'])) {
			$this->setError(JText::_('COM_DOSKA_WARNING_PROVIDE_VALID_NAME'));
			return FALSE;
		}
		
		if(trim($data['alias']) == '') {
			$data['alias'] = $data['title'];
			$data['alias'] = JApplicationHelper::stringURLSafe($data['alias']);
		}
		
		foreach($data['images'] as $k=>$img) {
			
			if(empty($img)) {
				continue;
			}
			
			$path = JPATH_SITE.'/';
			
			
			$image = new JImage($path.$img);
			//$result = $image->createThumbs(array('250x250','1024x768','800x600'),2,$path.'images/thumbs');
			
			
			$result = $image->generateThumbs(array('250x250'),2);
			
			
			if($result && is_array($result))  {
				$type = JImage::getImageFileProperties($path.$img)->type;
				if($type) {
					$move = $result[0]->toFile($path.$config->get('img_path').'/'.$config->get('img_thumb').'/'.basename($img),$type);
					if($move) {
						$result[0]->destroy();
						$image->destroy();
					}
				}
			}
			///1.jpg
			$data['images'][$k] = basename($img);
			
		}
		
		$registry = new Registry;
		$registry->loadArray($data['images']);
		
		$data['images'] = (string)$registry;
		
		if(parent::save($data)) {
			return TRUE;
		}
		return FALSE;
		
		
		
	}
	
	public function confirm($cid,$value) {
		
		if(!parent::canEditState(JArrayHelper::toObject($value))) {
			throw new RuntimeException(JFactory::getApplication()->enqueueMessage(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'),'warning'));
			return FALSE;
		}
		
		$table = $this->getTable();
		
		if($table->load($cid)) {
			
			if(!$table->confirm($cid,$value)) {
				
				$this->setError($table->getError());
				return FALSE;
			}
		}
		else {
			$this->setError($table->getError());
			return FALSE;
		}
		
		$this->cleanCache();
		
		return TRUE;
	}
	
	protected function canEditState($record)
	{
		$user = JFactory::getUser();
		$userId = $user->get('id');
		
		$messageId = (int)$record->id ? $record->id : 0;
		
		if(!$messageId) {
			return parent::canEditState($record);
		}
		
		if($user->authorise('core.edit.state', 'com_doska')) {
			return TRUE;
		}
		
		if($user->authorise('core.edit.state.own', 'com_doska')) {
			$message = $this->getItem($messageId);
			
			if(empty($message)) {
				return FALSE;
			}
			
			$id_author = $message->id_user;
			
			if($userId == $id_author) {
				return TRUE;
			}
		}
		
		throw new RuntimeException(JFactory::getApplication()->enqueueMessage(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'),'warning'));
		return FALSE;
	}
	
	
	public function getItem($pk = null) {
		if($item = parent::getItem($pk)) {
			
			
			$registry = new Registry;
			$registry->loadString($item->images);
			
			$config = JComponentHelper::getParams('com_doska');
			
			
			$item->images = $registry->toArray();
			
			//DIR.'/'.name.jpg
			foreach($item->images as $k=>$img) {
				if($img) {
					$item->images[$k] = $config->get('img_path').'/'.$img;
				}
				
			}
			return $item;
		}
	}
	

	

}